<template>
  <div id="dashboard">
    <div class="dashboard-header">
      <div class="back-button" @click="fanhui">返回管理页面</div>
      <h1>Zeno数据可视化</h1>
      <div class="header-controls">
        <div class="refresh-button" @click="manualRefresh" :class="{ 'refreshing': isRefreshing }">
          <span class="refresh-icon">🔄</span>
          <span class="refresh-text">{{ isRefreshing ? '刷新中...' : '手动刷新' }}</span>
        </div>
        <div class="auto-refresh-info">
          <span class="auto-refresh-text">自动刷新: {{ nextRefreshTime }}</span>
        </div>
        <TimeDisplay class="time-display" />
      </div>
    </div>
    
    <div class="dashboard-content">
      <div class="dashboard-grid">
        <!-- 左上角面板 -->
        <div class="grid-item left-top">
          <div class="panel-content">
            <LeftTop title="商品销售类别" ref="leftTopRef" />
          </div>
        </div>
        
        <!-- 右上角面板 -->
        <div class="grid-item right-top">
          <div class="panel-content">
            <RightTop title="类别数量" ref="rightTopRef" />
          </div>
        </div>
        
        <!-- 左下角面板 -->
        <div class="grid-item left-bottom">
          <div class="panel-content">
            <LeftBottom title="月度营收增长趋势" ref="leftBottomRef" />
          </div>
        </div>
        
        <!-- 右下角面板 -->
        <div class="grid-item right-bottom">
          <div class="panel-content">
            <RightBottom title="用户年龄分布" ref="rightBottomRef" />
          </div>
        </div>
        
        <!-- 中心地图区域 -->
        <div class="grid-item center-map">
          <ChinaMap3D ref="chinaMapRef" />
        </div>
      </div>
    </div>
  </div>
</template>
  
<script setup lang="js">
import { onMounted, onUnmounted, defineAsyncComponent, ref, nextTick } from 'vue';
import { useRouter } from 'vue-router';

// 导入组件
const TimeDisplay = defineAsyncComponent(() => import('../../components/Admincomponent/TimeDisplay.vue'));
const LeftTop = defineAsyncComponent(() => import('../../components/Admincomponent/LeftTop.vue'));
const RightTop = defineAsyncComponent(() => import('../../components/Admincomponent/RightTop.vue'));
const LeftBottom = defineAsyncComponent(() => import('../../components/Admincomponent/LeftBottom.vue'));
const RightBottom = defineAsyncComponent(() => import('../../components/Admincomponent/RightBottom.vue'));
const ChinaMap3D = defineAsyncComponent(() => import('../../components/Admincomponent/ChinaMap3D.vue'));

const router = useRouter();
const chinaMapRef = ref(null);
const leftTopRef = ref(null);
const rightTopRef = ref(null);
const leftBottomRef = ref(null);
const rightBottomRef = ref(null);

// 刷新相关状态
const isRefreshing = ref(false);
const nextRefreshTime = ref('');
let autoRefreshTimer = null;
let countdownTimer = null;
let nextRefreshTimestamp = null; // 添加下次刷新的时间戳

// 返回管理页面
const fanhui = () => {
  router.push('/admin/overview');
};

// 刷新所有组件数据
const refreshAllData = async () => {
  if (isRefreshing.value) return;
  
  isRefreshing.value = true;
  
  try {
    // 刷新各个组件
    const refreshPromises = [];
    
    if (leftTopRef.value && typeof leftTopRef.value.refresh === 'function') {
      refreshPromises.push(leftTopRef.value.refresh());
    }
    
    if (rightTopRef.value && typeof rightTopRef.value.refresh === 'function') {
      refreshPromises.push(rightTopRef.value.refresh());
    }
    
    if (leftBottomRef.value && typeof leftBottomRef.value.refresh === 'function') {
      refreshPromises.push(leftBottomRef.value.refresh());
    }
    
    if (rightBottomRef.value && typeof rightBottomRef.value.refresh === 'function') {
      refreshPromises.push(rightBottomRef.value.refresh());
    }
    
    if (chinaMapRef.value && typeof chinaMapRef.value.refresh === 'function') {
      refreshPromises.push(chinaMapRef.value.refresh());
    }
    
    // 等待所有刷新完成
    await Promise.allSettled(refreshPromises);
    
  } catch (error) {
    console.error('刷新数据时出错:', error);
  } finally {
    isRefreshing.value = false;
  }
};

// 手动刷新
const manualRefresh = async () => {
  await refreshAllData();
  // 重置自动刷新计时器
  startAutoRefresh();
};

// 格式化倒计时时间
const formatCountdown = (milliseconds) => {
  const hours = Math.floor(milliseconds / (1000 * 60 * 60));
  const minutes = Math.floor((milliseconds % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((milliseconds % (1000 * 60)) / 1000);
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
};

// 更新倒计时显示
const updateCountdown = () => {
  if (nextRefreshTimestamp) {
    const now = Date.now();
    const timeLeft = nextRefreshTimestamp - now;
    
    if (timeLeft <= 0) {
      // 倒计时结束，重置下次刷新时间
      nextRefreshTimestamp = now + 60 * 60 * 1000; // 1小时后
      nextRefreshTime.value = formatCountdown(60 * 60 * 1000);
    } else {
      nextRefreshTime.value = formatCountdown(timeLeft);
    }
  }
};

// 开始自动刷新
const startAutoRefresh = () => {
  // 清除现有定时器
  if (autoRefreshTimer) {
    clearInterval(autoRefreshTimer);
  }
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
  
  // 设置下次刷新的时间戳
  nextRefreshTimestamp = Date.now() + 60 * 60 * 1000; // 1小时后
  
  // 设置自动刷新定时器（每小时）
  autoRefreshTimer = setInterval(async () => {
    await refreshAllData();
    // 刷新后重置下次刷新时间
    nextRefreshTimestamp = Date.now() + 60 * 60 * 1000;
  }, 60 * 60 * 1000); // 1小时 = 60 * 60 * 1000 毫秒
  
  // 设置倒计时更新定时器（每秒更新一次）
  countdownTimer = setInterval(() => {
    updateCountdown();
  }, 1000); // 每秒更新一次
  
  // 立即更新一次倒计时
  updateCountdown();
};

// 组件挂载时启动自动刷新
onMounted(() => {
  startAutoRefresh();
});

// 组件卸载时清理定时器
onUnmounted(() => {
  if (autoRefreshTimer) {
    clearInterval(autoRefreshTimer);
  }
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
});
</script>

<style scoped>
#dashboard {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-image: url('/bg.jpg');
  background-size: cover;
  color: #fff;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.dashboard-header {
  height: 60px;
  width: 100%;
  background-image: url('/head_bg.png');
  background-size: 100% 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  z-index: 10;
}

.dashboard-header h1 {
  font-size: 28px;
  color: #fff;
  letter-spacing: 2px;
  text-shadow: 0 0 10px rgba(0, 183, 255, 0.7);
}

.back-button {
  position: absolute;
  left: 20px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 16px;
  color: #fff;
  cursor: pointer;
  padding: 6px 16px;
  border-radius: 4px;
  background-color: rgba(0, 183, 255, 0.3);
  border: 1px solid rgba(0, 183, 255, 0.6);
  transition: all 0.3s;
  text-align: center;
  min-width: 100px;
}

.back-button:hover {
  background-color: rgba(0, 183, 255, 0.6);
}

.header-controls {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
  gap: 20px;
}

.refresh-button {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #fff;
  cursor: pointer;
  padding: 6px 12px;
  border-radius: 4px;
  background-color: rgba(0, 183, 255, 0.3);
  border: 1px solid rgba(0, 183, 255, 0.6);
  transition: all 0.3s;
  min-width: 100px;
  justify-content: center;
  z-index: 1000;
  position: relative;
}

.refresh-button:hover {
  background-color: rgba(0, 183, 255, 0.6);
}

.refresh-button.refreshing {
  background-color: rgba(255, 193, 7, 0.6);
  border-color: rgba(255, 193, 7, 0.8);
  cursor: not-allowed;
}

.refresh-icon {
  font-size: 16px;
  transition: transform 0.3s;
}

.refresh-button.refreshing .refresh-icon {
  animation: spin 1s infinite linear;
}

.auto-refresh-info {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
  background-color: rgba(0, 0, 0, 0.3);
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid rgba(0, 183, 255, 0.4);
}

.time-display {
  position: static;
  transform: none;
}

.dashboard-content {
  flex: 1;
  padding: 0px;
  overflow: hidden;
  position: relative;
  z-index: 5;
  max-width: 100vw;
}

.dashboard-grid {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  grid-template-rows: 1fr 1fr;
  grid-template-areas: 
    "left-top center-map right-top"
    "left-bottom center-map right-bottom";
  gap: 0px;
  height: 100%;
  transition: all 0.3s ease;
  min-height: 600px; /* 添加最小高度 */
  width: 100%;
}

.panel-content {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.grid-item {
  border-radius: 4px;
  overflow: hidden;
  position: relative;
  transition: all 0.3s ease;
  min-height: 280px; /* 添加最小高度 */
}

/* 图表区域样式 */
.grid-item:not(.center-map) {
  background-color: rgba(1, 18, 71, 0.8);
  border: 1px solid rgba(0, 183, 255, 0.4);
  border-radius: 8px;
  box-shadow: 0 0 20px rgba(0, 102, 255, 0.2);
  backdrop-filter: blur(5px);
  min-width: 320px;
  width: 100%;
  position: relative;
  z-index: 5;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.grid-item:not(.center-map)::before {
  display: none;
}

/* 区域定位 */
.left-top { grid-area: left-top; justify-self: start; }
.right-top { grid-area: right-top; justify-self: end; }
.left-bottom { grid-area: left-bottom; justify-self: start; }
.right-bottom { grid-area: right-bottom; justify-self: end; }

/* 中心地图区域 */
.center-map {
  grid-area: center-map;
  grid-row: span 2;
  position: relative;
  z-index: 1;
  transition: all 0.3s ease;
  min-height: 600px; /* 增加最小高度 */
  min-width: 600px; /* 确保地图有足够的宽度 */
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}

/* 地图容器 */
#three-container {
  width: 100%;
  height: 100%;
  position: relative;
  z-index: 2;
  min-height: 600px; /* 确保容器有足够高度 */
}

/* 加载指示器 */
.loading-indicator {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #fff;
  z-index: 3;
}

.spinner {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 3px solid rgba(0, 183, 255, 0.3);
  border-top-color: rgba(0, 183, 255, 1);
  animation: spin 1s infinite linear;
  margin-bottom: 10px;
}

.loading-text {
  font-size: 16px;
  color: #fff;
  text-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes fadeOut {
  from { opacity: 0.8; }
  to { opacity: 0; }
}

</style>